/**
 * 搜索hooks
 * @Author: linzy
 * @Date: 2022-06-17
 * @function useSearch
 * @param {searchItem[]} searchItems - 搜索项数组
 * @param {function} onChange - 搜索change回调 onChange(values)
 * @param {object} values - 需要缓存的搜索数据
 * @param {function} tableFormSet - tableFormSet的hook方法,传入该项后则不需要使用onChange而会在onSearch里面处理
 * @param {button[]} buttons - buttons 按钮组 默认显示在左边 传参跟useButtons基本一致 增加了 align, 默认值为left
 * @property {string} type 表单类型
 * @property {string} name 字段名称
 * @property {string} placeholder 占位符
 * <caption>搜索项对象 searchItem</caption>
 * @returns [Search, searchProps, SearchRef];
 * @example
const searchItems = [
  { type: "input", name: "title", placeholder: "发布会名称"},
  { type: "select", name: "name1", placeholder: "生效状态",
    options: [
      { label: "未生效", value: "1" },
      { label: "已生效", value: "2" }
    ]
  },
  { type: "input", name: "name2", placeholder: "ID",
    props: {
      type: "number"
    },
  },
  { name: "startTime,endTime", type: "Range"}
];
const [Search, searchProps, searchRef] = useSearch({
  searchItems,
  // values: tableForm,
  onChange(values) {
    tableFormSet((state) => ({ ...state, page: 1, ...values }))
  },
});
<Search {...searchProps} />
 */
import React, { useRef, useEffect } from "react";
import { useForm } from "@/hooks";
import { Card } from "antd";
import styles from "./index.less";
import { getColProps, setDefaultAttrs } from "@/hooks/tools";

export default props => {
  const {
    searchItems = [],
    onChange,
    values = {},
    tableFormSet,
    buttons = [],
    initialValues = {},
  } = props;
  const formRef = useRef();
  const btnArr = [];
  buttons.forEach(item => {
    if (item.align === "right") {
      btnArr.unshift(item);
      item.style = { ...item.style, ...{ float: "right" } };
    } else {
      btnArr.push(item);
      item.style = {
        ...item.style,
        ...{ float: "left", marginRight: "8px", marginLeft: 0 }
      };
    }
  });
  const searchButtons = [
    {
      type: "",
      text: "清除",
      style: {
        float: "right",
        marginLeft: "8px"
      },
      onClick: form => {
        form.resetFields();
        form.setFieldsValue(initialValues);
      },
    },
    {
      text: "搜索",
      htmlType: "submit",
      style: {
        float: "right"
      }
    },
    ...btnArr
  ];
  searchItems.forEach(item => {
    item.props = {
      style: { width: "100%" },
      ...item.props
    };
    if (item.spanTimes) {
      item.colProps = getColProps(item.spanTimes);
    } else {
      item.colProps = getColProps();
    }
    if (/range/i.test(item.type)) {
      item.colProps = getColProps(2);
    }
    // 处理 dateRange
    if (item.types === "dateRange") {
      if (typeof item.placeholder === "string") {
        item.placeholder = [
          item.placeholder + "开始时间",
          item.placeholder + "结束时间"
        ];
      }
      setDefaultAttrs(item, {
        label: [],
        isSearch: true,
        type: "datetime",
        disabledDate: [false, false],
        required: [false, false],
        placeholder: ["开始时间", "结束时间"]
      });
    }
  });
  const [Form, formProps, transformDetail] = useForm({
    formItems: searchItems,
    buttons: searchButtons,
    rowProps: { gutter: 5 },
    buttonsFormItemProps: {
      className: styles.button_box,
      style: { marginBottom: 0 }
    },
    onSubmit(values) {
      // 对数据进行处理 如果为空则返回null id类数据返回数字类型
      for (const [key, val] of Object.entries(values)) {
        if (typeof val === "string") {
          values[key] = val.trim();
        }
        if (/id$/i.test(key) && /^\d+$/.test(val) && (val + "").length < 16) {
          values[key] = +val;
        } else if (val === "" || val === null) {
          values[key] = undefined;
        }
      }
      tableFormSet && tableFormSet(state => ({ ...state, page: 1, ...values }));
      onChange && onChange(values);
    }
  });
  const searchProps = {
    className: styles.useSearch
  };
  searchProps.children = <Form ref={formRef} {...formProps} />;
  useEffect(() => {
    const newValues = transformDetail({
      detail: values,
      formItems: searchItems
    });
    formRef.current && formRef.current.setFieldsValue(newValues);
  }, []);
  return [Card, searchProps, formRef];
};
